package chapter7.No7_5_线程中出现异常的处理;

/**
 * 捕获线程的异常
 * Created by Administrator on 2016/12/8.
 */
public class Main {
    public static void main(String[] args) {
        // 设置单个线程
        singleThreadException();

        // 设置所有线程的默认异常处理
        setDefaultExceptionHandler();
    }

    private static void setDefaultExceptionHandler() {
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            public void uncaughtException(Thread t, Throwable e) {
                System.out.println("线程：" + t.getName() + "出现异常");
                e.printStackTrace();
            }
        });
        MyThread b = new MyThread();
        b.setName("B");
        b.start();
    }

    private static void singleThreadException() {
        MyThread a = new MyThread();
        a.setName("A");
        a.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            public void uncaughtException(Thread t, Throwable e) {
                System.out.println("线程：" + t.getName() + "出现异常");
                e.printStackTrace();
            }
        });
        a.start();
    }
}
